package com.southminority.ethnic.controller.coures;

import com.southminority.ethnic.common.context.UserContext;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.controller.coures.vo.CourseEvaluationReqVo;
import com.southminority.ethnic.controller.coures.vo.CourseEvaluationSummaryVo;
import com.southminority.ethnic.controller.coures.vo.CourseEvaluationVo;
import com.southminority.ethnic.pojo.CourseEvaluation;
import com.southminority.ethnic.pojo.User;
import com.southminority.ethnic.service.course.CourseEvaluationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;

/**
 * 课程评价Controller
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "课程评价", description = "课程评价相关接口")
@RestController
@RequestMapping("/api/course/evaluation")
@CrossOrigin
@Validated
public class CourseEvaluationController {

    @Autowired
    private CourseEvaluationService courseEvaluationService;

    /**
     * 获取课程评价统计信息
     */
    @Operation(summary = "获取课程评价统计信息")
    @GetMapping("/summary/{courseId}")
    public R<CourseEvaluationSummaryVo> getEvaluationSummary(@PathVariable @NotNull Long courseId) {
        try {
            // 获取当前登录用户
            User currentUser = UserContext.getCurrentUser();
            Long userId = currentUser != null ? currentUser.getId() : null;

            CourseEvaluationSummaryVo summary = courseEvaluationService.getEvaluationSummary(courseId, userId);
            
            log.info("获取课程评价统计信息成功，课程ID: {}, 用户ID: {}", courseId, userId);
            return R.ok(summary);
            
        } catch (Exception e) {
            log.error("获取课程评价统计信息失败，课程ID: {}", courseId, e);
            return R.fail("获取评价信息失败：" + e.getMessage());
        }
    }

    /**
     * 添加或修改课程评价
     */
    @Operation(summary = "添加或修改课程评价")
    @PostMapping("/submit")
    public R<CourseEvaluationVo> submitEvaluation(@Valid @RequestBody CourseEvaluationReqVo reqVo) {
        try {
            // 获取当前登录用户
            User currentUser = UserContext.getCurrentUser();
            if (currentUser == null) {
                return R.fail("用户未登录");
            }

            // 添加或更新评价
            CourseEvaluation evaluation = courseEvaluationService.addOrUpdateEvaluation(
                reqVo.getCourseId(),
                currentUser.getId(),
                currentUser.getUsername(),
                reqVo.getRating(),
                reqVo.getContent()
            );

            // 转换为VO
            CourseEvaluationVo evaluationVo = new CourseEvaluationVo();
            BeanUtils.copyProperties(evaluation, evaluationVo);

            log.info("提交课程评价成功，课程ID: {}, 用户ID: {}", reqVo.getCourseId(), currentUser.getId());
            return R.ok(evaluationVo);

        } catch (Exception e) {
            log.error("提交课程评价失败，课程ID: {}", reqVo.getCourseId(), e);
            return R.fail("提交评价失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户对指定课程的评价
     */
    @Operation(summary = "获取用户对指定课程的评价")
    @GetMapping("/user/{courseId}")
    public R<CourseEvaluationVo> getUserEvaluation(@PathVariable @NotNull Long courseId) {
        try {
            // 获取当前登录用户
            User currentUser = UserContext.getCurrentUser();
            if (currentUser == null) {
                return R.fail("用户未登录");
            }

            CourseEvaluation evaluation = courseEvaluationService.getUserEvaluation(courseId, currentUser.getId());
            
            if (evaluation == null) {
                return R.ok(null); // 用户未评价该课程
            }

            // 转换为VO
            CourseEvaluationVo evaluationVo = new CourseEvaluationVo();
            BeanUtils.copyProperties(evaluation, evaluationVo);

            log.info("获取用户课程评价成功，课程ID: {}, 用户ID: {}", courseId, currentUser.getId());
            return R.ok(evaluationVo);

        } catch (Exception e) {
            log.error("获取用户课程评价失败，课程ID: {}", courseId, e);
            return R.fail("获取用户评价失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户是否已评价指定课程
     */
    @Operation(summary = "检查用户是否已评价指定课程")
    @GetMapping("/check/{courseId}")
    public R<Boolean> checkUserEvaluation(@PathVariable @NotNull Long courseId) {
        try {
            // 获取当前登录用户
            User currentUser = UserContext.getCurrentUser();
            if (currentUser == null) {
                return R.fail("用户未登录");
            }

            Boolean hasEvaluated = courseEvaluationService.hasUserEvaluated(courseId, currentUser.getId());

            log.info("检查用户评价状态成功，课程ID: {}, 用户ID: {}, 已评价: {}", 
                    courseId, currentUser.getId(), hasEvaluated);
            return R.ok(hasEvaluated);

        } catch (Exception e) {
            log.error("检查用户评价状态失败，课程ID: {}", courseId, e);
            return R.fail("检查评价状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取课程平均评分
     */
    @Operation(summary = "获取课程平均评分")
    @GetMapping("/rating/{courseId}")
    public R<Double> getCourseRating(@PathVariable @NotNull Long courseId) {
        try {
            Double averageRating = courseEvaluationService.getAverageRating(courseId);

            log.info("获取课程平均评分成功，课程ID: {}, 平均评分: {}", courseId, averageRating);
            return R.ok(averageRating);

        } catch (Exception e) {
            log.error("获取课程平均评分失败，课程ID: {}", courseId, e);
            return R.fail("获取平均评分失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户对指定课程的评价
     */
    @Operation(summary = "删除用户对指定课程的评价")
    @DeleteMapping("/delete/{courseId}")
    public R<Boolean> deleteUserEvaluation(@PathVariable @NotNull Long courseId) {
        try {
            // 获取当前登录用户
            User currentUser = UserContext.getCurrentUser();
            if (currentUser == null) {
                return R.fail("用户未登录");
            }

            Boolean deleted = courseEvaluationService.deleteUserEvaluation(courseId, currentUser.getId());

            if (deleted) {
                log.info("删除用户课程评价成功，课程ID: {}, 用户ID: {}", courseId, currentUser.getId());
                return R.ok(true);
            } else {
                log.warn("删除用户课程评价失败，课程ID: {}, 用户ID: {}", courseId, currentUser.getId());
                return R.fail("删除评价失败，可能评价不存在");
            }

        } catch (Exception e) {
            log.error("删除用户课程评价失败，课程ID: {}", courseId, e);
            return R.fail("删除评价失败：" + e.getMessage());
        }
    }
} 